package cn.edu.sdjzu.xg11.web;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.SessionAttributes;
import org.springframework.web.bind.support.SessionStatus;
import org.springframework.web.servlet.ModelAndView;

import cn.edu.sdjzu.xg11.domain.GraduateProject;
import cn.edu.sdjzu.xg11.domain.UserInfo;
import cn.edu.sdjzu.xg11.service.GraduateProjectService;
import cn.edu.sdjzu.xg11.service.GraduateProjectStatusService;
import cn.edu.sdjzu.xg11.service.GraduateTypeService;
import cn.edu.sdjzu.xg11.service.MajorService;
import cn.edu.sdjzu.xg11.service.ProjectCategoryService;

@Controller
@RequestMapping("/project")
//将名为"graduateProject"的对象存入Session中
//否则updateGraduateProject.jsp中被修改的graduateProject无法传递到update方法中。
@SessionAttributes("graduateProject")
public class ProjectController {
	/**
	 * Logger for this class
	 */
	private static final Logger logger = Logger
			.getLogger(ProjectController.class);

	@Autowired
	private GraduateProjectService graduateProjectService;
	@Autowired
	private ProjectCategoryService projectCategoryService;
	@Autowired
	private GraduateTypeService projectTypeService;
	@Autowired
	private MajorService majorService;
	@Autowired
	private GraduateProjectStatusService graduateProjectStatusService;
			
	// RequestMappingr的value属性可以省略"html"
	//本方法的@RequestMapping的路径相对于类定义 @RequestMapping("/project")
	@RequestMapping("/listGraduateProjects")
	public ModelAndView list() {
		if (logger.isDebugEnabled()) {
			logger.debug("list() - start");
		}
		System.out.println(graduateProjectService.getGraduateProjects());
		// 创建MV对象，第1参数为逻辑视图名称，加上bysj-servlet.xml中指定的前缀和后缀
		// 第2参数为模型名称，视图中可以通过该参数读取第3参数
		// 第3参数为模型数据
		ModelAndView mv = new ModelAndView("/project/listGraduateProjects",
				"graduateProjects",
				graduateProjectService.getGraduateProjects());

		if (logger.isDebugEnabled()) {
			logger.debug("list() - end");
		}
		return mv;
	}

	// 使用{id}作为url中的占位符
	@RequestMapping(value = "/deleteGraduateProject/{id}", method = RequestMethod.GET)
	// @pathVariable将url中的参数设置为方法参数
	public ModelAndView delete(@PathVariable("id") String id) {
		if (logger.isDebugEnabled()) {
			logger.debug("delete(String) - start");
		}

		Integer id_i = new Integer(id);
		graduateProjectService.deleteGraduateProject(id_i);
		// 刷新
		ModelAndView returnModelAndView = this.list();
		if (logger.isDebugEnabled()) {
			logger.debug("delete(String) - end");
		}
		return returnModelAndView;
	}
	@RequestMapping(value = "/deleteGraduateProjectByJS", method = RequestMethod.GET)
	public String delete(Model mm, @RequestParam String id){
		System.out.println("id to delete is " + id);
		return showGraduateProjectListJson(mm);
	}

	@RequestMapping(value = "/toAddGraduateProject")
	public ModelAndView toAddGraduateProject(){
		if (logger.isDebugEnabled()) {
			logger.debug("toAddGraduateProject() - start");
		}
	
		ModelAndView mv = new ModelAndView("/project/addGraduateProject");
		mv.addObject("graduateProject", new GraduateProject());
		prepareObjects(mv);

		if (logger.isDebugEnabled()) {
			logger.debug("toAddGraduateProject() - end");
		}
		return mv;
	}
	
	@RequestMapping(value = "/addGraduateProject", method = RequestMethod.POST)	
	public ModelAndView add(@Valid GraduateProject graduateProject,
			BindingResult bindingResult,
			HttpServletRequest request) {
		if (logger.isDebugEnabled()) {
			logger.debug("add(GraduateProject, HttpServletRequest) - start");
			logger.debug(graduateProject.getId()+"/"+graduateProject.getTitle());
		}
		if(bindingResult.hasErrors()){
			System.out.println(graduateProject.getTitle().length());
			System.out.println("********  error对象 开始********");
			System.out.println(bindingResult);
			System.out.println("********  error对象 结束********");
			ModelAndView mv = new ModelAndView("/project/addGraduateProject");
			prepareObjects(mv);
			return mv;
		}
		UserInfo userInfo = (UserInfo)request.getSession().getAttribute("userInfo");
		graduateProject.setGraduateProjectStatus(graduateProjectStatusService.getGraduateProject(1));
		graduateProject.setTeacher(userInfo.getTeacher());
		graduateProjectService.addGraduateProject(graduateProject);
		
		if (logger.isDebugEnabled()) {
			logger.debug("add(GraduateProject, HttpServletRequest) - end");
		}
		//如果不使用redirect的话，当前的地址仍然为"/bysj/project/addGraduateProject.html"。
		//如果刷新的话，会重新调用本方法，从而重复地增加一个设计题目 ！！！
//		return this.list().getViewName();转发模式，目标地址不变
		return new ModelAndView("redirect:/project/listGraduateProjects.html");//重向模式
	}
	
	// 使用{id}作为url中的占位符
	@RequestMapping(value = "/updateGraduateProject/{id}", method = RequestMethod.GET)
	// @pathVariable将url中的参数设置为方法参数
	public ModelAndView toUpdate(@PathVariable("id") String id,HttpServletRequest request) {
		if (logger.isDebugEnabled()) {
			logger.debug("toUpdate(String, HttpServletRequest) - start");
		}

		Integer id_i = new Integer(id);
		ModelAndView mv = new ModelAndView("/project/updateGraduateProject",
				"graduateProject",
				graduateProjectService.getGraduateProject(id_i));
		prepareObjects(mv);

		if (logger.isDebugEnabled()) {
			logger.debug("toUpdate(String, HttpServletRequest) - end");
		}
		return mv;
	}
	
	@RequestMapping(value = "/updateGraduateProject", method = RequestMethod.POST)	
	public String update(GraduateProject graduateProject,SessionStatus status) {
		if (logger.isDebugEnabled()) {
			logger.debug("update(GraduateProject, SessionStatus) - start");
		}

		graduateProjectService.updateGraduateProject(graduateProject);
		//将graduateProject从session中清除掉
		status.setComplete();
		if (logger.isDebugEnabled()) {
			logger.debug("update(GraduateProject, SessionStatus) - end");
		}
		//如果不使用redirect的话，当前的地址仍然为"/bysj/project/updateGraduateProject.html"。
		//如果刷新的话，会重新调用本方法，而status.setComplete清除了session，所以会出现
		//"Session attribute 'graduateProject' required - not found in session"		
//		return this.list().getViewName();转发模式，目标地址不变
		return "redirect:/project/listGraduateProjects.html";//重向模式
								  
	}

	private void prepareObjects(ModelAndView mv) {
		if (logger.isDebugEnabled()) {
			logger.debug("prepareObjects(ModelAndView) - start");
		}

		mv.addObject("categories", projectCategoryService.getProjectCategories());
		mv.addObject("types", projectTypeService.getProjectTypes());		
		mv.addObject("majors",majorService.getMajors());

		if (logger.isDebugEnabled()) {
			logger.debug("prepareObjects(ModelAndView) - end");
		}
	}
//	/project/graduateProjectToExcel.html
	@RequestMapping("/graduateProjectToExcel.html")
	public String toExcel(Model mm){
		mm.addAttribute("graduateProjectList",
				graduateProjectService.getGraduateProjects());
		return "graduateProjectListExcel";///bysj-servlet.xml中的<!-- Excel视图配置 -->bean
	}
	@RequestMapping("/showGraduateProjectListJson")
	public String showGraduateProjectListJson(Model mm){
		mm.addAttribute("graduateProjectList",
				graduateProjectService.getGraduateProjects());
		return "graduateProjectListJson";
	}
}
